package com.xiaoshuidi.cloud.module.member.controller.app.weixin;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.module.member.controller.app.auth.vo.AppAuthLoginRespVO;
import com.xiaoshuidi.cloud.module.member.service.user.MemberAuthService;
import com.xiaoshuidi.cloud.module.member.service.user.MemberUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;


@Tag(name = "租客APP - 微信")
@RestController
@RequestMapping("/member/wx-mp")
@Validated
@Slf4j
public class AppWxMpController {
    @Resource
    private WxMaService wxMaService;
    @Resource
    private MemberUserService userService;
    @Resource
    private MemberAuthService authService;

//    @Resource
//    private WxMpService mpService;
//
//    @PostMapping("/create-jsapi-signature")
//    @Operation(summary = "创建微信 JS SDK 初始化所需的签名",
//        description = "参考 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html 文档")
//    public CommonResult<WxJsapiSignature> createJsapiSignature(@RequestParam("url") String url) throws WxErrorException {
//        return success(mpService.createJsapiSignature(url));
//    }

    /**
     * 获取openid
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     *
     * @param appId
     * @param code
     * @return
     */
    @GetMapping("/code2session")
    @PermitAll
    public CommonResult<Object> code2session(@RequestParam("appId") String appId, @RequestParam("code") String code) {
        wxMaService.switchoverTo(appId);
        try {
            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
            return CommonResult.success(result.getOpenid());
        } catch (WxErrorException e) {
            switch (e.getError().getErrorCode()) {
                // 系统繁忙，此时请开发者稍候再试
                case -1:
                    throw new ServiceException(500, "系统繁忙, 请稍后再试");
                    //code 无效
                case 40029:
                    throw new ServiceException(406, "code无效");
                    //频率限制，每个用户每分钟100次
                case 45011:
                    throw new ServiceException(500, "请求频率太快了, 请稍后再试");
                    //高风险等级用户，小程序登录拦截
                case 40226:
                    throw new ServiceException(500, "高风险用户, 微信系统拦截");
                default:
                    throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR);
            }
        }
    }

    /**
     * 获取微信手机号
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
     *
     * @param appId
     * @param code
     * @return
     */
    @GetMapping("/get-phone")
    @PermitAll
    public CommonResult<AppAuthLoginRespVO> getPhone(@RequestParam("appId") String appId, @RequestParam("code") String code,
                                                     @RequestParam(value = "recommendId", required = false) Long recommendId) {
        log.info("获取微信手机号, appId: {}, code: {}, recommendId: {}", appId, code, recommendId);
        wxMaService.switchoverTo(appId);
        try {
            WxMaPhoneNumberInfo phoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(code);
            String phoneNumber = phoneNumberInfo.getPurePhoneNumber();
            return CommonResult.success(authService.phoneLogin(phoneNumber, recommendId));
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(), e.getError().getErrorMsg());
        }
    }

    @Autowired(required = false)
    public void setWxMaService(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }
}
